#include "Reactor/TcpServer.h"
#include "Reactor/EchoServer.h"
#include "Configuration.hh"
#include "Dictionary.hh"
#include "Cache/CacheManager.hh"
#include "Log/Log.hh"
#include "Cache/TimerManager.hh"
#include "Cache/SingnalRedis.hh"
#include "web/WebPageQuery.hh"
#include "SingleJieba.hh"
#include "Dictionary.hh"
#include "HONG.hh"
#include <string>
#include <iostream>
#include <signal.h>



using std::string;

void sig_handler(int signum){

    Log::error("收到了信号%d", signum);

    // 缓存写入文件
    auto& manager = CacheManager::createCacheManager()->getManager();
    auto& conf_map = Configuration::createConfig()->getConfigMap();
    manager.writeToFile(conf_map["cacahe_file"][0]);
    

    Log::info("缓存写入文件成功");
    Log::info("进程退出");

    TimerManager::destoryTimer();           // 销毁定时器
    CacheManager::destoryCacheManager();    // 销毁缓存管理器
    Dictionary::destoryDict();              // 销毁词典
    SingleJieba::destroyJieba();            // 销毁 jieba
    SingnalRedis::destoryRedis();           // 销毁 redis
    Log::destroyLog();                      // 销毁日志
    Configuration::destoryConfig();         // 销毁配置管理器

    exit(0);
}



int main(){
    
    auto& conf_map = Configuration::createConfig()->getConfigMap();
    Log::info("配置管理器启动");

    ::signal(SIGINT, sig_handler);
    Log::createLog(CONSOLE | ROLL);
    Log::info("日志启动");

    TimerManager::createTimer(1, 10);
    Log::info("定时器启动");

    CacheManager::createCacheManager();
    Log::info("缓存管理器启动");
    


    Dictionary::createInstance();
    Log::info("词典加载成功");

    EchoServer server(
        THREAD_NUM,
        QUEUE_SIZE,
        conf_map["ip"][0], 
        atoi(conf_map["port"][0].c_str())
    );

    server.start();

    return 0;
}